package com.bxl.netty.rpc.client.common.register;



import com.bxl.netty.rpc.common.future.CompletableFuture;
import com.bxl.netty.rpc.common.message.MsgResponseContent;
import com.bxl.netty.rpc.common.message.PackageMsg;

import java.util.concurrent.ConcurrentHashMap;

/**
 * <>
 *
 * @author baixl
 * @date 2021/2/25
 */
public class CallBackRegister<T> {
    private static ConcurrentHashMap<Long, CompletableFuture> mapping = new ConcurrentHashMap<Long, CompletableFuture>();

    public static void  register(long requestID, CompletableFuture cb){
        mapping.putIfAbsent(requestID, cb);
    }
    public static void runCallBack(PackageMsg<MsgResponseContent> req){
        CompletableFuture<Object> cf = mapping.get(req.getHeader().getRequestID());
        
        if(req.getContent().getCode() != 0){
            cf.exception(req.getContent().getDesc()); 
        }else{
            cf.complete(req.getContent().getContent());
        }
        removeCB(req.getHeader().getRequestID());
    }
    

    public static void removeCB(long requestID) {
        mapping.remove(requestID);
    }
}
